<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.member.member.list']" />
    <a-card class="general-card" :title="$t('menu.member.member.list')">

      <!-- 头部区域 -->
      <div class="header">
        <!-- 搜索栏 -->
        <div v-if="showQuery" class="header-query">
          <a-form ref="queryRef" :model="queryParams" layout="inline">
            <a-form-item field="username" hide-label>
              <a-input
                  v-model="queryParams.username"
                  placeholder="输入用户名搜索"
                  allow-clear
                  style="width: 150px"
                  @press-enter="handleQuery"
              />
            </a-form-item>

            <a-form-item field="createdAt" hide-label>
              <range-picker v-model="queryParams.createdAt" />
            </a-form-item>
            <a-form-item hide-label>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <template #icon><icon-search /></template>查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <!-- 操作栏 -->
        <div class="header-operation">
          <a-row>
            <a-col :span="16">
              <a-space>
                <a-button
                    v-permission="['member:member:export']"
                    :loading="exportLoading"
                    type="primary"
                    status="warning"
                    @click="handleExport"
                >
                  <template #icon><icon-download /></template>导出
                </a-button>
              </a-space>
            </a-col>
            <a-col :span="12">
              <right-toolbar v-model:show-query="showQuery" @refresh="fetchData"/>
            </a-col>
          </a-row>
        </div>
      </div>


      <a-table
          row-key="id"
          :data="memberList"
          :loading="loading"
          :pagination="{
              showTotal: true,
              showPageSize: true,
              total: total,
              current: queryParams.page,
            }"
          :bordered="false"
          :size="size"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
          @selection-change="handleSelectionChange"
          :row-selection="{
              type: 'checkbox',
              showCheckedAll: true,
              onlyCurrent: false,
            }"
      >

        <template #columns>
          <a-table-column title="ID" data-index="id" :width="85" />
          <a-table-column title="用户名" data-index="username" :width="120" />

          
          <a-table-column title="头像" align="center" :width="50">
            <template #cell="{ record }">
              <a-avatar>
                <img :src="record.avatar" alt="头像" />
              </a-avatar>
            </template>
          </a-table-column>

          <a-table-column title="昵称" data-index="nickName" :width="120" />
          <a-table-column title="真实姓名" data-index="realName" :width="120" />
          <a-table-column title="邮箱" data-index="email" :width="120" />
          <a-table-column title="手机" data-index="phone" :width="120" />
          <a-table-column title="省份" data-index="province" :width="120" />
          <a-table-column title="城市" data-index="city" :width="120" />
          <a-table-column title="最后登录" data-index="lastLogin" :width="120" />

          <a-table-column
              title="操作"
              align="center"
              fixed="right"
              :width="80"
          >
            <template #cell="{ }">
              <a-button
                  v-permission="['member:member:update']"
                  type="text"
                  size="small"
                  title="修改"
              >
                <template #icon><icon-edit /></template>
              </a-button>


            </template>
          </a-table-column>
        </template>


      </a-table>
    </a-card>



  </div>



</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref, toRefs} from 'vue';
  import {useI18n} from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {PolicyRecord} from '@/api/list';
  import {
    pageMember,
    switchMemberStatus,
    MemberResponse,
    MemberParam,
    MemberResponseList
  } from "@/api/member/member";
  import checkPermission from '@/utils/check-permission';
  import {DictResponseState} from "@/store/modules/dict/types";
  import {AxiosResponse} from "axios";
  import {HttpResponse} from "@/api/interceptor";

  const showQuery = ref(true);

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const { proxy } = getCurrentInstance() as any;
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);

  const size = ref<SizeProps>('medium');
  const checkedIds = ref<Array<number>>([]);
  const title = ref('');
  const single = ref(true);
  const multiple = ref(true);

  const data = reactive({
    queryParams: {
      username: undefined,
      status: 1,
      createdAt: undefined,
      page: 1,
      size: 10,
      sort: ['createdAt,desc'],
    },

    rules: {
      username: [{ required: true, message: '请输入管理员用户名' }],
      password: [{ required: true, message: '请输入管理员密码' }],
      roleIds: [{ required: true, message: '请选择所属角色' }],
    },

  });
  const { queryParams,rules } = toRefs(data);

  const memberList = ref<MemberResponse[]>([]);
  const total = ref(0);

  const member = ref<MemberResponse>({
    id: undefined,
    username: '',
    avatar: '',
    googleKey: '',
    googleStatus: undefined,
    realName: '',
    email: '',
    phone: '',
    gender: undefined,
    birthday: '',
    countryCode: '',
    country: '',
    province: '',
    city: '',
    district: '',
    gradeLevel: '',
    loginCount: '',
    loginErrorCount: '',
    lastLogin: '',
  });

  const fetchData = (params: MemberParam = {...queryParams.value}) => {
    setLoading(true);
    pageMember(params).then(res => {
      memberList.value = res.data.list;
      total.value = Number(res.data.total);
    }).finally(() => {
      setLoading(false);
    });

  };

  fetchData();

  const visible = ref(false);

  const roleLoading = ref(false);
  const roleOptions = ref<DictResponseState[]>([]);

  const handleQuery = () => {
    console.log("handleQuery", queryParams);
    fetchData();
  };

  const resetQuery = () => {
    proxy.$refs.queryRef.resetFields();
    handleQuery();
  };

  const handlePageChange = (current: number) => {
    queryParams.value.page = current;
    fetchData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    queryParams.value.size = pageSize;
    fetchData();
  };

  const handleSelectionChange = (rowKeys: Array<any>) => {
    checkedIds.value = rowKeys;
    single.value = rowKeys.length !== 1;
    multiple.value = !rowKeys.length;
  };


  const handleCancel = () => {
    visible.value = false;
    memberRoleVisible.value =false;
    proxy.$refs.formRef?.resetFields();
    proxy.$refs.userRoleFormRef?.resetFields();
  };


  const memberRoleVisible = ref(false);

  const detailLoading = ref(false);
  const detailVisible = ref(false);

  const handleDetailCancel = () => {
    detailVisible.value = false;
  };

  const exportLoading = ref(false);
  const handleExport = () => {
    if(exportLoading.value) return;

    exportLoading.value = true;
    proxy
        .download('/member/member/member/export', { ...queryParams.value }, '用户数据')
        .finally(() => {
          exportLoading.value = false;
        });

  }


</script>

<script lang="ts">
export default {
  name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.header {
  padding-bottom: 10px;
}
</style>
